﻿using SmallJob.Model;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace SmallShop.Services.Code
{
    public class EmailFactory
    {
        public EmailFormat EmailFormat;
        public Dictionary<string, string> DictionaryEmail;
        private const string REGEX_TEXT = "[{][a-zA-Z0-9]+[}]";

        public EmailFactory()
        {
            InitDictionaryDefault();
        }
        public EmailFactory(EmailFormat emailformat)
        {
            EmailFormat = emailformat;
            InitDictionaryDefault();
        }

        private void InitDictionaryDefault()
        {
            DictionaryEmail = new Dictionary<string, string>();
        }

        public string ReplaceBodyWithDictionary()
        {
            return ReplaceWithDictionary(EmailFormat.BodyEmail);
        }
        public string ReplaceSubjectWithDictionary()
        {
            return ReplaceWithDictionary(EmailFormat.SubjectMail);
        }
        public string ReplaceWithDictionary(string source)
        {
            Regex regex = new Regex(REGEX_TEXT);
            MatchCollection collection = regex.Matches(source);
            if (collection.Count > 0)
            {
                foreach (var item in collection)
                {
                    var key = GetOriginString(item.ToString());
                    if (DictionaryEmail.ContainsKey(key))
                    {
                        Regex regextemp = new Regex("[{]" + key + "[}]");
                        source = regextemp.Replace(source, DictionaryEmail[key]);
                    }
                }
            }
            return source;
        }
        private string GetOriginString(string input)
        {
            return input.Substring(1, input.Length - 2);
        }

        public void FillDataToDictionary(string source)
        {
            var entrys = source.Split(';');
            foreach (var item in entrys)
            {
                var knv = item.Split(':');
                var key = knv[0];
                var value = knv[1];
                DictionaryEmail.Add(key, value);
            }
        }
        public Dictionary<string, string> GetDictionary()
        {
            return DictionaryEmail;
        }
    }
}